var mongoose = require('mongoose');
var User = require('../models/user.model');

exports.create = function (req, res, next) {
    const user = new User(req.body); // req.body
    user.save(function (err, data) {
        if (err) {
            console.log(err);
        } else {
            res.json(data);
        }
    });

}

exports.update = function (req, res, next) {
    const id = req.params.id;
    User.findByIdAndUpdate(id, { $set: req.body }, { new: false })
        .then(data => {
            res.json(data);
        })
}

exports.remove = function (req, res, next) {
    const id = req.params.id;
    User.findByIdAndRemove(id, function (err, data) {
        res.json({ "message": "delete one ok" });
    })
}

exports.removes = function (req, res, next) {
    var ids = req.body.ids;
    console.log(ids);
    if (ids.length > 0) {
        User.remove({ _id: { $in: ids } })
            .then(data => {
                res.json({ "message": "delete some ok" })
            })
    }
}

exports.list = function (req, res, next) {
    var page = (req.body.page) ? req.body.page : 1;
    var limit = (req.body.limit) ? req.body.limit : 2;
    var queryCondition = {};
    if (req.body.name && req.body.name.trim().length > 0) {
        name = req.body.name;
        queryCondition = {
            "name": new RegExp(name, "i")
        }
    }

    User.paginate(queryCondition, { page: page, limit: limit }, function (err, results) {
        res.json(results)


    })

}

exports.login = function (req, res, next) {
    var name = req.body.name;
    var password = req.body.password;
    var that = res
    User.findOne({ name: name, password: password }).then(res => {
        if (res) {
            that.json(res)
        } else {
            that.json('0')
        }
    })
}

exports.check = function (req, res, next) {
    var name = req.body.name;
    var that = res
    User.findOne({ name: name}).then(res => {
        if (res) {
            that.json(res)
        } else {
            that.json('0')
        }
    })
}